// pages/my/my.js
var http = require('../../utils/https');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{},
    balance: '0.00',
    couponCount: 0,
    points: 0,
    grade:'',//用户VIP等级
  },

  //前往售后页面
  toMyBack(){
    wx.navigateTo({
      url: '/my/pages/mzhMyBackGoods/mzhMyBackGoods',
    })
  }, 

  // 前往我的自提订单
  toMyself(){
    wx.navigateTo({
      url: '/my/pages/mzhMyselfGet/mzhMyselfGet',
    })
  },
  // 前往地址页面
  toAddress(){
    wx.navigateTo({
      url: '/my/pages/mzhAddress/mzhAddress',
    })
  },

  // 前往订单页面
  toOrders(){
    wx.navigateTo({
      url: '/my/pages/xtxOrders/xtxOrders',
    })
  },

  // 前往设置页面
  toSetup(){
    wx.navigateTo({
      url: '/my/pages/xtxSetup/xtxSetup',
    })
  },

  onLoad(options) {
    var userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo:userInfo
    })
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
      return
    }
    this.fetchAllStats(userInfo.userId)
  },
  onShow(){
    var userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo:userInfo
    })
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
      return
    }
    this.fetchAllStats(userInfo.userId)
  },

  fetchAllStats(userId){
    this.fetchBalance(userId)
    this.fetchCouponCount(userId)
    this.fetchPoints(userId)
    this.getVipPoint(userId)
  },

  fetchBalance(userId){
    var that = this
    http.GET(`/balance/user/${userId}`, {}, function(res){
      if(res.code === 200){
        var obj = res.data || {}
        var val = obj.balance
        if(val === undefined || val === null){
          val = obj.amount
        }
        if(val === undefined || val === null){
          val = obj.total
        }
        if(val === undefined || val === null){
          val = obj.money
        }
        var num = 0
        if(typeof val === 'number'){
          num = val
        }else if(typeof val === 'string' && val.trim() !== ''){
          num = parseFloat(val)
          if(isNaN(num)) num = 0
        }
        that.setData({ balance: num.toFixed(2) })
      } else {
        that.handleAuthExpired(res)
      }
    }, function(err){
      console.error('余额获取失败:', err)
    })
  },

  fetchCouponCount(userId){
    var that = this
    http.GET(`/coupon/receive/user/${userId}/availableCount`, {}, function(res){
      if(res.code === 200){
        var count = res.data
        if(typeof count !== 'number'){
          count = parseInt(count || 0)
          if(isNaN(count)) count = 0
        }
        that.setData({ couponCount: count })
      } else {
        that.handleAuthExpired(res)
      }
    }, function(err){
      console.error('优惠券数量获取失败:', err)
    })
  },

  fetchPoints(userId){
    var that = this
    http.GET(`/point/user/${userId}`, {}, function(res){
      if(res.code === 200){
        var obj = res.data || {}
        var pts = obj.points
        if(pts === undefined || pts === null){
          pts = obj.point
        }
        if(pts === undefined || pts === null){
          pts = obj.score
        }
        if(pts === undefined || pts === null){
          pts = obj.integral
        }
        var num = 0
        if(typeof pts === 'number'){
          num = pts
        }else if(typeof pts === 'string' && pts.trim() !== ''){
          num = parseInt(pts)
          if(isNaN(num)) num = 0
        }
        that.setData({ points: num })
      } else {
        that.handleAuthExpired(res)
      }
    }, function(err){
      console.error('积分获取失败:', err)
    })
  },
  getVipPoint(userId){
    var that = this
    http.GET(`/system/point/getUserVipPoint/${userId}`, {}, function(res){
      if(res.code === 200){
        console.log(res);
        var gradePoint = res.data.vipPoint
        if(gradePoint>=10000){
          that.setData({
            grade:"LV4"
          })
        }else if(gradePoint>=5000){
          that.setData({
            grade:"LV3"
          })
        }else if(gradePoint>=1000){
          that.setData({
            grade:"LV2"
          })
        }else{
          that.setData({
            grade:"LV1"
          })
        }
      } else {
        that.handleAuthExpired(res)
      }
    }, function(err){
      console.error('等级失败:', err)
    })
  },

  handleAuthExpired(res){
    wx.showToast({
      title: '认证过期，请重新登录',
      icon: 'none',
      duration: 1500
    })
    setTimeout(()=>{
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
    }, 1500)
  }
})